from catalog.models import Author, Book, BookInstance
from django.contrib.auth.models import User
from datetime import date, timedelta

def run():
    # 清空原有数据
    Author.objects.all().delete()
    Book.objects.all().delete()

    # 插入作者
    authors = [
        Author(first_name='鲁迅', last_name='周树人', date_of_birth='1881-09-25', date_of_death='1936-10-19'),
        Author(first_name='老舍', last_name='舒庆春', date_of_birth='1899-02-03', date_of_death='1966-08-24'),
        Author(first_name='曹雪芹', last_name='', date_of_birth='1715-01-01', date_of_death='1763-01-01'),
        Author(first_name='金庸', last_name='查良镛', date_of_birth='1924-03-10', date_of_death='2018-10-30'),
        Author(first_name='J.K.', last_name='Rowling', date_of_birth='1965-07-31'),
        Author(first_name='George', last_name='Orwell', date_of_birth='1903-06-25', date_of_death='1950-01-21'),
    ]
    for author in authors:
        author.save()

    # 插入图书
    books = [
        Book(title='呐喊', author=authors[0], summary='鲁迅短篇小说集', isbn='9787530214781'),
        Book(title='骆驼祥子', author=authors[1], summary='老舍代表作', isbn='9787020002207'),
        Book(title='红楼梦', author=authors[2], summary='中国古典小说巅峰', isbn='9787020002208'),
        Book(title='射雕英雄传', author=authors[3], summary='金庸武侠小说', isbn='9787020002209'),
        Book(title='哈利·波特与魔法石', author=authors[4], summary='魔法世界的冒险', isbn='9780747532699'),
        Book(title='1984', author=authors[5], summary='反乌托邦小说', isbn='9780451524935'),
    ]
    for book in books:
        book.save()

    # 创建普通用户
    user1, _ = User.objects.get_or_create(username='reader1')
    user1.set_password('test1234')
    user1.save()
    user2, _ = User.objects.get_or_create(username='reader2')
    user2.set_password('test1234')
    user2.save()

    # 创建图书实例（借阅记录）
    BookInstance.objects.create(book=books[0], imprint='2023年第一版', due_back=date.today()+timedelta(days=7), borrower=user1, status='o')
    BookInstance.objects.create(book=books[1], imprint='2022年第二版', due_back=date.today()+timedelta(days=3), borrower=user2, status='o')
    BookInstance.objects.create(book=books[2], imprint='2021年第三版', due_back=date.today()+timedelta(days=14), status='a')
    BookInstance.objects.create(book=books[0], imprint='2023年第一版', due_back=date.today()+timedelta(days=1), borrower=user2, status='o')
    BookInstance.objects.create(book=books[1], imprint='2022年第二版', due_back=date.today()+timedelta(days=10), status='a')

    print('示例作者和图书数据已导入。')

    print('测试数据已添加！') 